<template>
  <v-container fluid fill-height class="version-wrapper">
    <v-layout row wrap justify-center>
      <v-flex md8>
        <v-flex md2 xs12>
        <v-layout row class="text-xs-center">
            <v-flex md4>
              <v-btn :disabled="currentYear <= 2018" icon @click="switchYear(currentYear - 1)">
                <v-icon>arrow_back_ios</v-icon>
              </v-btn>
            </v-flex>
            <v-flex md4 d-flex align-center>
              <span class="title">
                {{ currentYear }}
              </span>
            </v-flex>
            <v-flex md4>
              <v-btn icon @click="switchYear(currentYear + 1)">
                <v-icon>arrow_forward_ios</v-icon>
              </v-btn>
            </v-flex>
          </v-layout>
      </v-flex>
      <v-layout row nowrap>
        <v-flex md2 xs2>
        <div class="datepicker-panel datepicker-month-selector">

          <!-- <span class="datepicker-month-button" v-for="(month, index) in locale.months" :class="{
                    'datepicker-selected': currentMonthName === month
                  }" :key="month" @click="switchMonth(index)">
            <v-badge color="red">
              <span slot="badge">12</span>
              {{ month }}
            </v-badge>
          </span> -->

          <v-list>
          <v-list-tile ripple v-for="(month, index) in locale.months" :class="{
                    'datepicker-selected': currentMonthName === month
                  }" :key="index" avatar @click="switchMonth(index)">
            <!-- <v-list-tile-avatar>
              <v-icon color="yellow" v-if="index == (new Date()).getMonth()">fa-star</v-icon>
            </v-list-tile-avatar> -->
            <v-list-tile-content class="month-item-content">
              <v-list-tile-title class="text-xs-center">{{ month }}</v-list-tile-title>
            </v-list-tile-content>
            <v-list-tile-avatar class="hidden-xs-only">
              <!-- <v-avatar size="24"  color="red"> -->
                <span class="body-3 black--text selected--text">{{yearCount[index]}}</span>
              <!-- </v-avatar> -->
            </v-list-tile-avatar>
          </v-list-tile>
        </v-list>

        </div>
      </v-flex>
      <v-flex md10 xs10>
        <div class="datepicker-body">
          <div class="datepicker-body-content">
            <transition name="datepicker-view">
              <transition-group tag="div" class="datepicker-panel datepicker-calendar" :class="calendarClasses" name="datepicker-month">
                <div class="datepicker-panel datepicker-month" v-for="month in [currentDate]" :key="month.getMonth()">
                  <div class="datepicker-week">
                    <span v-for="(day, index) in locale.days" :key="index" v-if="index >= firstDayOfAWeek">{{ day }}</span>
                    <span v-for="(day, index) in locale.days" :key="index" v-if="index < firstDayOfAWeek">{{ day }}</span>
                  </div>
                  <div class="datepicker-days">
                    <span class="datepicker-empty" v-for="day in prefixEmptyDays" :key="'day-empty-'+day"></span>
                    <div class="datepicker-day" v-for="(day, index) in daysInMonth" :key="'day-'+day.i + index">
                      <div class="datepicker-day-body" @click="toDayList(currentYear, month.getMonth() + 1 ,day.i)">
                        <span class="datepicker-day-button subheading font-weight-bold" :class="{
                          'datepicker-selected': isSelectedDay(day.i),
                          'datepicker-today': isToday(day.i),
                          'datepicker-disabled': isDisabled(day.i)
                        }"  @click.stop="selectDate(day.i)">{{ day.i }}</span>
                        <!-- <v-chip  small label text-color="white" flat class="py-0 px-2 mb-1 hidden-xs-only" dark :color="pallet[day.i % 4]" v-for="(item, ind) in day.items"
                          :key="ind + item.projectName">
                          {{item.projectName}}
                        </v-chip> -->
                        <v-layout row wrap justify-space-between align-start align-content-start>
                          <v-tooltip  md6 xs6 top v-for="(item, ind) in day.items"
                          :key="ind + item.projectName" class="px-1 mb-1 hidden-xs-only white--text task-item green-bg"  :class="item.status == 2 ? 'red-bg': 'green-bg'">
                            <v-flex slot="activator"  dark  >{{item.projectName}}{{itemType[item.type]}}</v-flex>
                            <span>{{item.projectName}}{{itemType[item.type]}}</span>
                          </v-tooltip>
                        </v-layout>
                        <v-chip small text-color="white" color="red" class="hidden-md-and-up" v-if="day.items"> {{day.items ? day.items.length : 0 }}</v-chip>

                      </div>
                    </div>
                  </div>
                </div>

              </transition-group>
            </transition>
          </div>
        </div>
      </v-flex>
      </v-layout>

      </v-flex>

    </v-layout>

  </v-container>
</template>

<script>
import addMonths from "date-fns/add_months";
import startOfMonth from "date-fns/start_of_month";
import subMonths from "date-fns/sub_months";
import getDate from "date-fns/get_date";
import getDay from "date-fns/get_day";
import getDaysInMonth from "date-fns/get_days_in_month";
import getMonth from "date-fns/get_month";
import getYear from "date-fns/get_year";
import isEqual from "date-fns/is_equal";
import isSameDay from "date-fns/is_same_day";
import isToday from "date-fns/is_today";
import setDate from "date-fns/set_date";
import setMonth from "date-fns/set_month";
import setYear from "date-fns/set_year";

const daysInAWeek = 7;

const getElements = (el, selector) => {
  if (el && el.querySelector) {
    return el.querySelectorAll(selector);
  }

  return false;
};

import * as version from "../../api/version";
export default {
  data: () => ({
    currentDate: null,
    selectedDate: null,
    showDialog: false,
    monthAction: null,
    currentView: "day",
    contentStyles: {},
    availableYears: null,
    pallet: {
      "0": "light-blue-bg",
      "1": "red-bg",
      "2": "amber-bg",
      "3": "cyan-bg",
      "4": "blue-bg",
      "5": "indigo-bg",
      "6": "purple-bg",
      "7": "orange-bg",
    },
    monthIndex: 1,
    daysInMonth: null,
    locale: {
      startYear: 1900,
      endYear: 2099,
      dateFormat: "YYYY-MM-DD",
      days: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
      shorterDays: ["日", "一", "二", "三", "四", "五", "六"],
      longerDays: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
      months: [
        "一月",
        "二月",
        "三月",
        "四月",
        "五月",
        "六月",
        "七月",
        "八月",
        "九月",
        "十月",
        "十一月",
        "十二月"
      ],
      shorterMonths: [
        "一",
        "二",
        "三",
        "四",
        "五",
        "六",
        "七",
        "八",
        "九",
        "十",
        "十一",
        "十二"
      ]
    },
    yearCount: [],
    isMobile: false,
    itemType: {
      '0': '',
      '1': '-客',
      '2': '-服',
    }
  }),
  mounted() {
    this.monthIndex = new Date().getMonth();

    this.isMobile = !!window.navigator.appVersion.match(/(Android|iPhone)/i)
    if(this.isMobile) {
      this.locale.days = this.locale.shorterDays
      this.locale.months = this.locale.shorterMonths
    }
    $Vue.$off('areaCodeChange')
    $Vue.$on('areaCodeChange', ()=>{
       this.getMonthCount();
      this.getYearCount();
    })
    // this.getMonthCount();
    // this.getYearCount();
  },
  computed: {
    firstDayOfAWeek() {
      // normalize
      let firstDayOfAWeek = 1;
      if (Number.isNaN(firstDayOfAWeek) || !Number.isFinite(firstDayOfAWeek)) {
        return 0;
      }
      firstDayOfAWeek = Math.floor(firstDayOfAWeek) % daysInAWeek;
      firstDayOfAWeek += firstDayOfAWeek < 0 ? daysInAWeek : 0;
      return firstDayOfAWeek;
    },
    calendarClasses() {
      if (this.monthAction === "next") {
        return "next";
      }
      return "previous";
    },
    firstDayOfMonth() {
      return startOfMonth(this.currentDate).getDay();
    },
    prefixEmptyDays() {
      let prefixEmptyDays = this.firstDayOfMonth - this.firstDayOfAWeek;
      prefixEmptyDays += prefixEmptyDays < 0 ? daysInAWeek : 0;
      return prefixEmptyDays;
    },
    currentDay() {
      if (this.selectedDate) {
        return getDate(this.selectedDate);
      }

      return getDate(this.currentDate);
    },
    currentMonth() {
      return getMonth(this.currentDate);
    },
    currentMonthName() {
      return this.locale.months[this.currentMonth];
    },
    currentYear() {
      return getYear(this.currentDate);
    }
  },
  watch: {
    mdDate() {
      this.currentDate = this.mdDate || new Date();
      this.selectedDate = this.mdDate;
    },
    currentDate(next, previous) {
      this.$nextTick().then(() => {
        if (previous) {
          this.setContentStyles();
        }
        this.getMonthCount();
        this.getYearCount();
      });
    },
    currentView() {
      this.$nextTick().then(() => {
        if (this.currentView === "year") {
          const activeYear = getElements(
            this.$el,
            ".datepicker-year-button.datepicker-selected"
          );

          if (activeYear.length) {
            activeYear[0].scrollIntoView({
              behavior: "instant",
              block: "center",
              inline: "center"
            });
          }
        }
      });
    }
  },
  methods: {
    getMonthCount() {
      let month = this.currentMonth + 1;
      let year = this.currentYear;
      let days = getDaysInMonth(this.currentDate);
      this.daysInMonth = [];
      let daysArray = [];
      for (let i = 1; i <= days; i++) {
        daysArray.push({
          i: i
        });
      }
      let opt = {
        fromTime: new Date(`${year}/${month}/1 00:00:00`).getTime(),
        toTime: new Date(`${year}/${month}/31 23:59:59`).getTime()
      };
      version.getMonthCount.r(opt).then(({ data }) => {
        if (data.result == 0) {
          // console.log(JSON.stringify(data.data.dataList));
          data.data.dataList.forEach((item, i) => {
            if(item.projectName == '其他') {
            data.data.dataList.splice(i, 1)
            }
          })
          data.data.dataList.forEach((item, i) => {
            console.log(_.last(new Date(item.createTime).toLocaleDateString().split('/')))
            let index = _.last(new Date(item.createTime).toLocaleDateString().split('/'));
            if (!daysArray[index - 1].items) {
              daysArray[index - 1] = {
                i: index,
                items: [item]
              };
            } else {
              daysArray[index - 1].items.push(item)
            }
          });
        }
        this.daysInMonth = daysArray;
      });
    },
    getYearCount() {
      let opt = {
        fromTime: new Date(`${this.currentYear}/1/1 00:00:00`).getTime(),
        toTime: new Date(`${this.currentYear + 1}/1/1 00:00:00`).getTime(),
      };
      version.getYearCount.r(opt).then(({ data }) => {
        let ycount = []
        if (data.result == 0) {
          data.data.dataList.forEach((item, i)=>{
            ycount[item.months - 1] = item.totalRow
          })
          this.yearCount = ycount

        } else {
          ycount.length = 12
          this.yearCount = _.fill(ycount,0)
        }
      });
    },
    setContentStyles() {
      const months = getElements(this.$el, ".datepicker-month");

      if (months.length) {
        const nextMonth = months[months.length - 1];
        this.contentStyles = {
          height: nextMonth.offsetHeight + 10 + "px"
        };
      }
    },
    setAvailableYears() {
      const { startYear, endYear } = this.locale;
      let counter = startYear;
      let years = [];

      while (counter <= endYear) {
        years.push(counter++);
      }

      this.availableYears = years;
    },
    handleDisabledDateByArray(date) {
      return this.mdDisabledDates.some(disabledDate =>
        isSameDay(disabledDate, date)
      );
    },
    isDisabled(day) {
      if (this.mdDisabledDates) {
        const targetDate = setDate(this.currentDate, day);

        if (Array.isArray(this.mdDisabledDates)) {
          return this.handleDisabledDateByArray(targetDate);
        } else if (typeof this.mdDisabledDates === "function") {
          return this.mdDisabledDates(targetDate);
        }
      }
    },
    isSelectedDay(day) {
      return isEqual(this.selectedDate, setDate(this.currentDate, day));
    },
    isToday(day) {
      return isToday(setDate(this.currentDate, day));
    },
    previousMonth() {
      this.monthAction = "previous";
      this.currentDate = subMonths(this.currentDate, 1);
    },
    nextMonth() {
      this.monthAction = "next";
      this.currentDate = addMonths(this.currentDate, 1);
    },
    switchMonth(index) {
      this.monthAction = index > this.monthIndex ? "previous" : "next";
      this.monthIndex = index;
      this.currentDate = setMonth(this.currentDate, index);
      this.currentView = "day";
    },
    switchYear(year) {
      this.currentDate = setYear(this.currentDate, year);
      this.currentView = "month";
    },
    selectDate(day) {
      this.currentDate = setDate(this.currentDate, day);
      this.selectedDate = this.currentDate;

      if (this.mdImmediately) {
        this.$emit("update:mdDate", this.selectedDate);
        this.closeDialog();
      }
    },
    closeDialog() {
      this.$emit("closed");
    },
    onClose() {
      this.closeDialog();
    },
    onCancel() {
      this.closeDialog();
    },
    onConfirm() {
      this.$emit("update:mdDate", this.selectedDate);
      this.closeDialog();
    },
    resetDate() {
      this.currentDate = this.mdDate || new Date();
      this.selectedDate = this.mdDate;
      this.currentView = "day";
    },
    toVersionDetails(item) {
      console.log(item);
      this.$router.push(`/details/:${item.version}`);
    },
    toDayList(year, month, day) {
      this.$router.push(`/record?date=${year}-${month}-${day}`);
    }
  },
  created() {
    this.setAvailableYears();
    this.resetDate();
  }
};
</script>

<style lang="less" scoped>
@light-blue: #03a9f4;
@calendar-width: 100%;
@transition-stand-timing: cubic-bezier(0.25, 0.8, 0.25, 1);
@transition-default-timing: cubic-bezier(0.4, 0, 0.2, 1);
.datepicker-body {
  width: @calendar-width;
  position: relative;
  overflow: hidden;
  transition: width 0.3s @transition-stand-timing;
  will-change: width;
}

.datepicker-body-content {
  overflow: hidden;
  transition: height 0.35s @transition-default-timing;
  will-change: height;
}

.datepicker-panel {
  display: flex;
  flex-direction: column;
  transition: 0.35s @transition-default-timing;
  transition-property: transform, opacity;
  will-change: transform, opacity;
  &.datepicker-view-enter,
  &.datepicker-view-leave-active {
    transform: translate3d(0, 100%, 0);
  }
  &.previous {
    .datepicker-month-enter {
      transform: translate3D(-100%, 0, 0);
      .datepicker-month-trigger {
        transform: translate3D(-30%, 0, 0);
      }
    }
    .datepicker-month-leave-active {
      transform: translate3D(100%, 0, 0);
    }
  }
  &.next {
    .datepicker-month-enter {
      transform: translate3D(100%, 0, 0);
      .datepicker-month-trigger {
        transform: translate3D(30%, 0, 0);
      }
    }
    .datepicker-month-leave-active {
      transform: translate3D(-100%, 0, 0);
    }
  }
}

.datepicker-month {
  top: 8px;
  bottom: auto;
  flex-direction: column;
  transition: 0.35s @transition-default-timing;
  transition-property: transform, opacity;
  will-change: transform, opacity;
}

.datepicker-week {
  display: flex;
  align-items: center;
  span {
    flex: 1;
    height: 3.5rem;
    line-height: 3rem;
    font-size: 18px;
    text-align: center;
    border: 1px solid #ddd;
  }
}

.datepicker-days {
  @day-width: 100%;
  display: flex;
  flex-wrap: wrap;

  .datepicker-empty,
  .datepicker-day {
    display: flex;
    align-items: start;
    justify-content: start;
    flex: 0 1 @day-width / 7;
    border: 1px solid #ddd;
    height: 9.17rem;
    overflow: hidden;
    transition: 0.3s @transition-default-timing;

  }
  .datepicker-day-body {
    height: 9rem;
    width: 100%;
    transition: 0.3s @transition-default-timing;

    .md6,.xs6 {
      flex-basis: 48%;
    }
  }
  .datepicker-day:hover {
    cursor: pointer;
    &:hover{
    background-color: rgba(166, 166, 166, 0.1);
  }
  }
  .datepicker-day-button {
    @width: 2rem;
    display: block;
    width: @width;
    min-width: @width;
    height: @width;
    border-radius: @width;
    transition: 0.3s @transition-default-timing;
    line-height: @width;
    text-align: center;
  }
  
  .datepicker-today {
    font-weight: 700;
    background: @light-blue;
    color: white;
  }
  .datepicker-disabled {
    pointer-events: none;
  }
}

.datepicker-month-button {
  text-align: center;
  line-height: 4rem;
  height: 4rem;
  cursor: pointer;
  border-bottom: 1px solid #ddd;
}

.datepicker-selected {
  background: @light-blue;
  color: white;
}
.datepicker-selected {
    font-weight: 700;
    .selected--text {
      color: white!important;
    }
  }
.font-weight-bold {
  font-weight: bold;
}

.month-item-content {

}

.list {
  border-left: 1px solid #ddd;
}

.task-item {
  height: 1.2rem;
  font-size: 11px;
  border-radius: 4px;
  background-color:  #7672d4;
}
.light-blue-bg {
  background-color:  #03A9F4;
}
.red-bg{
  background-color:  #F44336;
}
.amber-bg{
  background-color:  #009688;
}
.cyan-bg{
  background-color:  #00BCD4;
}
.blue-bg{
  background-color:  #2196F3;
}
.indigo-bg{
  background-color:  #3F51B5;
}
.purple-bg{
  background-color:  #673AB7;
}
.orange-bg{
  background-color:  #FFC107;
}

@media only screen and (min-width: 960px) {
 .list {
  border-bottom: 1px solid #ddd;
}

}
</style>


